package com.codyy.lib_common.base.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.codyy.lib_common.base.viewmodel.BaseViewModel
import com.kennyc.view.MultiStateView

/**
 * Fragment懒加载
 */
abstract class BaseFragment : Fragment {
    constructor() : super()
    constructor(@LayoutRes contentLayoutId: Int) : super(contentLayoutId)

    protected var mRootView: View? = null

    private var mIsHasData = false//是否加载过数据

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewModelAction()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (mRootView == null) {
            mRootView = inflater.inflate(getLayoutRes(), container, false)
        }
        return mRootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    override fun onResume() {
        super.onResume()
        lazyLoadData()
    }

    private fun lazyLoadData() {
        if (!mIsHasData) {
            mIsHasData = true
            initData()
        }
    }

    private fun initViewModelAction() {
        this.getViewModel()?.let { baseViewModel ->
            baseViewModel.mStateLiveData.observe(this, Observer {
                it?.run {
                    when (this) {
                        MultiStateView.ViewState.LOADING -> showLoading()
                        MultiStateView.ViewState.CONTENT -> dismissLoading()
                        MultiStateView.ViewState.EMPTY -> dismissLoading()
                        MultiStateView.ViewState.NONETWORK -> dismissLoading()
                        MultiStateView.ViewState.ERROR -> {
                            dismissLoading()
                        }
                    }
                    changeViewState(this)
                }

            })
        }
    }

    open fun setVisible(isVisible: Boolean) {
    }

    abstract fun getLayoutRes(): Int

    abstract fun initView()

    open fun initData() {

    }

    open fun getViewModel(): BaseViewModel? = null

    open fun showLoading() {

    }

    open fun dismissLoading() {

    }

    open fun changeViewState(state: MultiStateView.ViewState) {

    }

}